import { STORAGE_KEY } from '@/common/config.js'

// 需要登录的页面
const loginPages = [
    '/pages/loan/apply',
    '/pages/loan/repay',
    '/pages/loan/records',
    '/pages/user/index',
    '/pages/user/auth',
    '/pages/user/bank-card',
    '/pages/user/settings'
]

// 不需要登录的页面
const publicPages = [
    '/pages/login/index',
    '/pages/login/register',
    '/pages/login/forgot',
    '/pages/common/agreement',
    '/pages/common/privacy'
]

// 检查登录状态
const checkLoginStatus = () => {
    const userInfo = uni.getStorageSync(STORAGE_KEY.USER_INFO)
    return !!userInfo
}

// 路由守卫
export function routerGuard(options) {
    // 获取当前页面路径
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const currentPath = `/${currentPage.route}`

    // 检查是否是公共页面
    if (publicPages.includes(currentPath)) {
        return true
    }

    // 其他页面都需要登录
    if (!checkLoginStatus()) {
        uni.showToast({
            title: '请先登录',
            icon: 'none'
        })

        setTimeout(() => {
            uni.redirectTo({
                url: '/pages/login/index'
            })
        }, 1500)

        return false
    }

    return true
} 